package org.stvd.controller.admin;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.stvd.common.Consts;
import org.stvd.common.aspectj.lang.annotation.Log;
import org.stvd.common.aspectj.lang.enums.BusinessType;
import org.stvd.common.security.SecurityUserHolder;
import org.stvd.common.utils.InterfaceResult;
import org.stvd.controller.BaseController;
import org.stvd.core.dto.QueryResult;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.admin.Department;
import org.stvd.entities.admin.Guids;
import org.stvd.entities.admin.Resources;
import org.stvd.entities.admin.RoleMenu;
import org.stvd.entities.admin.Roles;
import org.stvd.service.admin.DepartmentService;
import org.stvd.service.admin.GuidsService;
import org.stvd.service.admin.MenusService;
import org.stvd.service.admin.ResourcesService;
import org.stvd.service.admin.RolesService;
import org.stvd.service.admin.UsersService;
import org.stvd.service.common.CommonService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 系统角色-控制类
 * @author houzx
 */
@Api(tags = "系统角色接口类")
@Controller
@RequestMapping("/admin/roles")
public class RolesController extends BaseController {

    @Autowired
    RolesService rolesService;
    @Autowired
    MenusService menusService;
    @Autowired
    ResourcesService resourcesService;
    @Autowired
    UsersService usersService;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    private GuidsService guidsService;
    @Autowired
    private CommonService commonService;
    
    @Value("${top_guid}")
    private String topGuid = "";
    
    private String tmpURL = "/admin/roles/";

    /**
     * 角色管理请求
     * @param roles
     * @return
     */
    @ApiIgnore
    @GetMapping(value = "management")
    public String onPageLoad(@ModelAttribute("roles") Roles roles) {
        if(!StringUtil.isEmpty(request.getParameter("gid"))) {
            roles.setGuid(request.getParameter("gid"));
        }
        if(StringUtil.isEmpty(roles.getGuid())) {
            roles.setGuid(StringUtil.isEmpty(topGuid) ? Consts.GUID :topGuid);
        }
        loadRoleResource(roles);
        return tmpURL + "RolesManagement.html";
    }
    
    @ApiIgnore
    @PostMapping(value = "management")
    public String onPageAction(@ModelAttribute("roles") Roles roles) {
        loadRoleResource(roles);
        return tmpURL + "RolesManagement.html";
    }
    
    // 加载角色管理资源（公共方法）
    private void loadRoleResource(Roles roles) {
        List<Department> depList = null;
        boolean isManage = commonService.checkManage(SecurityUserHolder.getCurrentUserId(), roles.getGuid());
        if(isManage) {
            depList =  departmentService.findAllDepByGuid(roles.getGuid());
        }else{
            String depId = SecurityUserHolder.getCurrentMaxAuthDepId(roles.getGuid());
            depList = departmentService.getAllChildDepartment(depId, roles.getGuid());
        }
        String depIdStr = roles.getDepId();
        if(StringUtil.isEmpty(depIdStr)) {
            if(depList!=null && depList.size() > 0) {
                for (Department department : depList) {
                    if(!StringUtil.isEmpty(depIdStr)) {
                        depIdStr += ",";
                    }
                    depIdStr += department.getDepId();
                }
            }
        }
        QueryResult<Roles> queryResult = rolesService.getRoleQueryResult((pageNo - 1) * pageSize, pageSize,
            depIdStr, roles.getGuid());
        map.put("queryResult", queryResult);
        map.put("guidsList", guidsService.listGuidByUserId(SecurityUserHolder.getCurrentUserId()));
        map.put("guids", guidsService.findByPk(Guids.class, StringUtil.isEmpty(topGuid) ? Consts.GUID :topGuid));
        map.put("dep", SecurityUserHolder.getCurrentMaxAuthDep(roles.getGuid()));
        map.put("depList", depList);
        map.put("roles", roles);
    }
    
    // 获取编辑页面的初始化菜单和资源
    private void getInitList(String guid) {
        String depId = SecurityUserHolder.getCurrentMaxAuthDepId(guid);
        String userId = SecurityUserHolder.getCurrentUserId();
        boolean isManage = commonService.checkManage(userId, guid);
        if(isManage) {
             map.put("depList", departmentService.findAllDepByGuid(guid));
             map.put("resList", resourcesService.findResourceAll(guid));
             map.put("menuList", menusService.findAll(guid));
        }else{
            map.put("depList", departmentService.getAllChildDepartment(depId, guid));
            map.put("resList", resourcesService.findResourcesByUid(userId, guid));
            map.put("menuList", menusService.findByUid(userId, guid));
        }
        map.put("dep", SecurityUserHolder.getCurrentMaxAuthDep(guid));
    }

    // 获取当前用户分配的角色及资源信息
    private void getCurrentList(ModelMap map, String roleId, String guid) {
        // 获取当前角色菜单信息
        List<RoleMenu> rolemenuList = rolesService.findRoleMenuByRoleId(roleId, guid);
        String[] menuSelected = new String[rolemenuList.size()];
        for (int i = 0; i < rolemenuList.size(); i++) {
            menuSelected[i] = rolemenuList.get(i).getMenuId();
        }
        // 获取当前角色资源信息
        List<Resources> rolereslist = resourcesService.findResourcesByRoleId(roleId, guid);
        String[] resSelected = new String[rolereslist.size()];
        for (int i = 0; i < rolereslist.size(); i++) {
            resSelected[i] = rolereslist.get(i).getResId();
        }
        map.put("menuSelected", menuSelected);
        map.put("resSelected", resSelected);
    }

    /**
     * 角色新增请求
     * @param guid GUID
     * @param roles
     * @return
     */
    @ApiIgnore
    @GetMapping(value = "add/{guid}")
    public String onAddLoad(@PathVariable String guid, 
        @ModelAttribute("roles") Roles roles) {
        roles.setGuid(guid);
        getInitList(guid);
        return tmpURL + "RolesAdd.html";
    }

    @ApiOperation(value = "新增角色信息")
    @Log(title = "新增角色信息", businessType = BusinessType.INSERT)
    @PostMapping(value = "add")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onAddAction(
        @Valid @ModelAttribute("roles") Roles roles, 
        BindingResult bindingResult) throws Exception {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        String[] menuSelected = request.getParameterValues("checkedMenu");
        String[] resSelected = request.getParameterValues("checkedRes");
        if (bindingResult.hasErrors()) {
            result.setError(bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        // 角色信息
        roles.setRoleId(StringUtil.getRandomUUID());
        roles.setEnable("T");
        rolesService.insert(roles);
        // 菜单权限
        rolesService.insertRoleMenu(roles.getRoleId(), menuSelected, roles.getGuid());
        // 资源权限
        rolesService.insertRoleRes(roles.getRoleId(), resSelected, roles.getGuid());

        map.clear();
        result.setMsg("新增成功！");
        return result;
    }

    /**
     * 系统角色修改
     * @param roleId
     * @return
     */
    @ApiIgnore
    @GetMapping(value = "edit/{roleId}")
    public String onEditLoad(@PathVariable String roleId) {
        Roles roles = rolesService.findByPk(Roles.class, roleId);
        if(roles!=null) {
            map.put("roles", roles);
            getInitList(roles.getGuid());
            getCurrentList(map, roles.getRoleId(), roles.getGuid());
        }else {
            map.put("errorMsg", "角色信息获取错误，请返回重试！");
        }
        return tmpURL + "RolesEdit.html";
    }

    @ApiOperation(value = "修改角色信息")
    @Log(title = "修改角色信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "edit")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onEditAction(
        @Valid @ModelAttribute("roles") Roles roles, BindingResult bindingResult) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        String[] menuSelected = request.getParameterValues("checkedMenu");
        String[] resSelected = request.getParameterValues("checkedRes");
        if (bindingResult.hasErrors()) {
            result.setError(bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        // 修改角色
        rolesService.update(roles);
        // 菜单权限
        rolesService.insertRoleMenu(roles.getRoleId(), menuSelected, roles.getGuid());
        // 资源权限
        rolesService.insertRoleRes(roles.getRoleId(), resSelected, roles.getGuid());

        map.clear();
        result.setMsg("修改成功！");
        return result;
    }

    /**
     * 系统角色删除
     * @param roleId
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "删除角色信息")
    @Log(title = "删除角色信息", businessType = BusinessType.DELETE)
    @PostMapping(value = "del")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onRoleDelete(String roleId) throws Exception {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        Roles roles = rolesService.findByPk(Roles.class, roleId);
        try {
            rolesService.deleteRole(roleId, roles.getGuid());
            // 菜单权限
            rolesService.insertRoleMenu(roles.getRoleId(), null, roles.getGuid());
            // 资源权限
            rolesService.insertRoleRes(roles.getRoleId(), null, roles.getGuid());
            result.setMsg("角色‘" + roles.getRoleName() + "’删除成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setError("删除角色‘" + roles.getRoleName() + "’失败！<br/>失败原因：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取机构下角色信息
     * @param request
     * @return
     */
    @ApiOperation(value = "获取全部角色列表")
    @PostMapping(value="queryall")
    @ResponseBody
    public List<Roles> getDepRoleList(String depId, String guid){
        List<Roles> roleList = rolesService.findRolesByDepId(depId, guid);
        return roleList;
    }
    
    /**
     * 获取机构下角色信息(用户权限标识)
     * @param request
     * @return
     */
    @ApiOperation(value = "获取用户角色列表")
    @PostMapping(value="queryrole")
    @ResponseBody
    public List<Roles> getUserDepRoleList(String userId, String depId, String guid){
        List<Roles> roleList = rolesService.findRolesByDepId(depId, guid);
        if(roleList!=null && roleList.size() > 0) {
            List<Roles> userRoleList = rolesService.getRolesByUserId(userId, guid);
            if(userRoleList!=null && userRoleList.size() > 0) {
                for (Roles roles : roleList) {
                    for (Roles userRole : userRoleList) {
                        if (roles.getRoleId().equals(userRole.getRoleId())) {
                            roles.setChecked(true);
                            break;
                        }
                    }
                }
            }
        }
        return roleList;
    }
}
